"use client";
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Select,
  Table,
  Tree,
  Modal,
} from "antd";
import { system } from "@/forent-api/api";
import { Pagination } from "@/utils/db/dbTools";
import React, { useEffect, useState } from "react";
import { userTableColumns } from "@/app/[locale]/system/dept/tools";
import { App } from "antd";
import { getSysDicts, SysDictProps } from "@/app/gloableTools";

const SystemDeptContent: React.FC = () => {
  const [form] = Form.useForm();
  const [userForm] = Form.useForm();
  const [deptModelTitle, setDeptModelTitle] = useState("");
  const [userModelTitle, setUserModelTitle] = useState("");
  const { message, modal, notification } = App.useApp();

  const [treeData, setTreeData] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentNode, setCurrentNode] = useState<any>(null);

  // 用户
  const [isUserModalVisible, setIsUserModalVisible] = useState(false);

  const [userTableData, setUserTableData] = useState([]);
  const [userRecord, setUserRecord] = useState<any>(null);
  const [roleOptions, setRoleOptions] = useState<any[]>([]);

  // 用户角色
  const [userRole, setUserRole] = useState<SysDictProps[]>([]);
  // 系统机构等级
  const [sysDeptLevel, setSysDeptLevel] = useState<number>(2);

  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  useEffect(() => {
    getDeptListAction();
    loadUserRole();
  }, []);

  // 获取用户角色
  const loadUserRole = async () => {
    const res = await getSysDicts("sys_user_role");
    setUserRole(res);
    const level = await getSysDicts("sys_dept_level");
    if (level.length > 0) {
      setSysDeptLevel(parseInt(level[0].value.toString() || "2"));
    }
  };

  const onAdd = () => {
    if (currentNode?.level > sysDeptLevel) {
      message.info(`机构层级不能超过${sysDeptLevel}级`);
      return;
    }
    setDeptModelTitle("添加机构");
    showModal("add", currentNode);
  };

  // 获取机构列表
  const getDeptListAction = () => {
    system.getDeptList({}).then((res) => {
      setTreeData(res.data);
      setCurrentNode(null);
    });
  };

  /**
   * 树节点的点击
   * @param info
   */
  const onTreeSelect = (info: any) => {
    if (info.selected) {
      setCurrentNode(info?.node);
    } else {
      setCurrentNode(null);
    }
  };

  // 显示弹窗
  const showModal = (action: string, record?: any) => {
    form?.setFieldsValue({ action }); // 设置当前操作类型
    setIsModalVisible(true);
  };

  const onDelete = () => {
    // 删除逻辑
    if (!currentNode) {
      message.info("请选择机构");
      return;
    }

    // 加个确认弹窗
    modal.confirm({
      title: "确认删除",
      content: "确定要删除该机构吗？",
      onOk: () => {
        return system.deleteDept({ id: currentNode.key }).then((res) => {
          setCurrentNode(null);
          getDeptListAction();
        });
      },
    });
  };

  // 编辑机构
  const onEdit = () => {
    if (!currentNode) {
      message.info("请选择机构");
      return;
    }
    // 编辑逻辑
    setDeptModelTitle("编辑机构");
    showModal("edit", currentNode);
    form?.setFieldsValue({ dept_name: currentNode.title });
  };

  // 提交
  const handleOk = async () => {
    try {
      const values = await form?.validateFields();

      if (form.getFieldValue("action") == "add") {
        if (currentNode?.level >= sysDeptLevel) {
          message.info(`机构层级不能超过${sysDeptLevel}级`);
          return;
        }
        if (currentNode) {
          values.parent_id = currentNode.key;
          values.level = currentNode?.level + 1;
        } else {
          values.level = 1;
        }
        values.max_level = sysDeptLevel;
        await system.addDept(values);
        message.success("机构添加成功");
      } else {
        await system.updateDept({ ...values, id: currentNode.key });
        message.success("机构更新成功");
      }

      // 只有在所有操作成功后才关闭弹窗和重置表单
      setCurrentNode(null);
      form?.resetFields();
      getDeptListAction();
      setIsModalVisible(false);
    } catch (errorInfo) {
      // 验证失败时不关闭弹窗，让用户看到验证错误信息
      console.log("表单验证失败:", errorInfo);
    }
  };

  // 取消
  const handleCancel = () => {
    setIsModalVisible(false);
    form?.resetFields();
  };

  // 获取用户列表
  useEffect(() => {
    fetchUserList();
  }, [pagination.current, currentNode?.key]);

  // 获取用户列表
  const fetchUserList = async () => {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      dept_id: currentNode?.key,
    };
    system.getUserList(params).then((response) => {
      console.log("用户列表", response);
      setUserTableData(response.data.data);
      setPagination({
        ...pagination,
        current: response.data.page,
        total: response.data.total as number,
      });
    });
  };

  // 显示用户弹窗
  const showUserModal = (action: string, record?: any) => {
    userForm?.setFieldsValue({ action }); // 设置当前操作类型
    setIsUserModalVisible(true);
    // 获取所有角色
    system.getAllRoles().then(res => {
      setRoleOptions(res.data);
    });
  };

  // 提交用户表单
  const handleUserOk = async () => {
    try {
      const values = await userForm?.validateFields();
      console.log("values==========>>>>", values,userForm)

      if (userForm.getFieldValue("action") == "addUser") {
        await system.addUser({ ...values, dept_id: currentNode.key });
        message.success("用户添加成功");
      } else {
        await system.updateUser({ ...values, id: userRecord.id });
        message.success("用户更新成功");
      }
      setIsUserModalVisible(false);
      userForm?.resetFields();
      fetchUserList();
    } catch (errorInfo) {
      // 验证失败时不关闭弹窗，让用户看到验证错误信息
      console.log("表单验证失败:", errorInfo);
    }
  };

  // 取消用户表单
  const handleUserCancel = () => {
    setIsUserModalVisible(false);
    userForm?.resetFields();
  };

  // 添加用户
  const onAddUser = () => {
    if (!currentNode) {
      message.info("请选择机构");
      return;
    }
    setUserModelTitle("添加用户");
    showUserModal("addUser", currentNode);
  };

  // 编辑用户
  const onEditUser = (action: string, record: any) => {
    setUserModelTitle("编辑用户");
    showUserModal(action, record);
    setUserRecord(record);
    userForm?.setFieldsValue({
      ...record,
      password: "",
    });
  };

  // 删除用户
  const onDeleteUser = async (record: any) => {
    // 删除逻辑
    if (!record) {
      message.info("请选择用户");
      return;
    }
    // 加个确认弹窗
    modal.confirm({
      title: "确认删除",
      content: "确定要删除该用户吗？",
      onOk: async () => {
        await system.deleteUser({ id: record.id });
        message.success("用户删除成功");
        fetchUserList();
      },
    });
  };

  const handleTableChange = (pagination: any, filters: any, sorter: any) => {
    setPagination((prev: any) => ({ ...prev, current: pagination.current }));
  };

  return (
    <div className="">
      <Row gutter={4}>
        <Col
          span={5}
          className="h-full rounded-lg"
          style={{ overflow: "auto", height: "100%" }}
        >
          <div className="mx-1 p-2 bg-white rounded-lg">
            <div className="flex justify-between">
              <Button type="primary" onClick={onAdd} className="mb-4">
                添加机构
              </Button>
              <Button type="default" onClick={onEdit} className="mb-4">
                编辑机构
              </Button>
              <Button danger type="primary" onClick={onDelete} className="mb-4">
                删除机构
              </Button>
            </div>
            <Tree
              showLine
              defaultExpandAll={false}
              treeData={treeData}
              onSelect={(selectedKeys, info) => onTreeSelect(info)}
            />
          </div>
        </Col>
        <Col span={19} className="h-full  rounded-lg ">
          <div className="mx-1 p-2 bg-white rounded-lg">
            <div className="flex justify-between">
              <Button type="primary" onClick={onAddUser} className="mb-4">
                添加用户
              </Button>
            </div>
            <Table
              rowKey={(record) => record.id}
              dataSource={userTableData}
              columns={userTableColumns(onEditUser, onDeleteUser)}
              pagination={{ ...pagination, position: ["bottomCenter"] }}
              onChange={handleTableChange}
            />
          </div>
        </Col>
      </Row>
      <Modal
        title={deptModelTitle}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form}>
          {/* 获取当前机构的上级机构 */}
          {currentNode && deptModelTitle == "添加机构" && (
            <Form.Item label="上级机构" labelCol={{ span: 4 }}>
              <Input disabled value={currentNode.title} />
            </Form.Item>
          )}
          <Form.Item
            name="dept_name"
            label="机构名称"
            labelCol={{ span: 4 }}
            rules={[{ required: true, message: "请输入机构名称" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={userModelTitle}
        open={isUserModalVisible}
        onOk={handleUserOk}
        onCancel={handleUserCancel}
      >
        <Form
          form={userForm}
          layout="horizontal"
          initialValues={{ status: "0", sex: "0" }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="user_name"
                label="账户："
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码："
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input placeholder="请输入密码" type="password" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="nick_name"
                label="昵称："
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: "请输入昵称" }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="sex"
                label="性别："
                labelCol={{ span: 5 }}
                rules={[{ required: false, message: "请选择性别" }]}
              >
                <Select>
                  <Select.Option value="0">男</Select.Option>
                  <Select.Option value="1">女</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="role_type"
                label="用户角色"
                rules={[{ required: true, message: "请选择用户角色" }]}
              >
                <Select placeholder="请选择用户角色" options={roleOptions} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="状态：" labelCol={{ span: 5 }}>
                <Select>
                  <Select.Option value="0">正常</Select.Option>
                  <Select.Option value="1">停用</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item
                name="remark"
                className="ml-1"
                label="备注："
                labelCol={{ span: 2 }}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default function SystemDept() {
  return (
    <div>
      <SystemDeptContent />
    </div>
  );
}
